<template>
  <div>
    <van-search
      @input="gosearch"
      shape="round"
      v-model.trim="value"
      placeholder="请输入搜索关键词"
    />
    <template v-if="value">
      <van-cell title="最佳匹配" />
      <van-list
        :immediate-check="false"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <music-item :item="item" v-for="item in list" :key="item.id" />
      </van-list>
    </template>
    <template v-else>
      <van-cell title="热门搜索" />
      <van-tag
        @click="hotsearch(item.first)"
        v-for="item in hotKey"
        :key="item.first"
        size="large"
        color="#c20c0c"
        text-color="#000"
        plain
        round
        type="primary"
        >{{ item.first }}</van-tag
      >
    </template>
  </div>
</template>

<script>
import { getflag, searchSong } from '@/api/search.js'
import MusicItem from '../../components/MusicItem.vue'
export default {
  components: { MusicItem },
  data () {
    return {
      hotKey: [],
      value: '',
      error: false,
      list: [],
      loading: false,
      finished: false,
      page: 1,
      limit: 20,
      count: 0
    }
  },

  created () {
    this.gethotkey()
  },

  methods: {
    hotsearch (i) {
      this.value = i
      this.gosearch()
    },
    gosearch () {
      this.list = []
      this.page = 1
      this.count = 0
      this.finished = false
      this.loading = true
      this.error = false
      clearTimeout(this.id)
      if (this.value) {
        this.id = setTimeout(() => {
          this.onLoad()
        }, 700)
      }
    },
    async gethotkey () {
      try {
        const res = await getflag()
        this.hotKey = res.data.result.hots
      } catch (err) {}
    },
    async onLoad () {
      try {
        const res = await searchSong({
          keywords: this.value,
          limit: this.limit,
          offset: (this.page - 1) * this.limit
        })
        if (res.data.result.songs) {
          this.list.push(...res.data.result.songs)
          this.page++
          this.count = res.data.result.songCount
        } else {
          this.count = 0
        }
      } catch (err) {
        this.finished = false
        this.loading = false
        this.error = true
        return
      }
      this.loading = false
      if (this.list.length >= this.count) {
        this.finished = true
      }
    }
  }
}
</script>

<style scoped lang="less">
.van-tag {
  margin: 5px 5px 5px 10px;
}
</style>
